package org.llu.urldirect.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/urlRedirect")
public class TestURLController {
    //ModelAndView
    @RequestMapping("/modelAndView")
    public ModelAndView test(HttpServletRequest request , HttpServletResponse response) {
        String url = request.getParameter("url");
        url = "redirect:" + url;
        return new ModelAndView(url);
    }

    /**
     * 通过返回string的方式重定向
     * @param url
     * @return
     */
    @RequestMapping("/string")
    // 加上这个注解会直接返回字符串 , 可加可不加，前后端分离的情况，基本都是这种直接返回字符串的。
    // @ResponseBody
    public String redirectBystring(String url){
        return "redirect:" + url;
    }
    // sendRedirect 的方式跳转
    @RequestMapping("/sendRedirect")
    public void redirectBySendRedirect(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = request.getParameter("url");
        response.sendRedirect(url);
    }

    //  通过设置文件头进行重定向
    @RequestMapping("/setHeader")
    public void redirectBySetHeader(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = request.getParameter("url");
        response.setHeader("Location", url);
        response.setStatus(302);
    }

    // 重定向
    @GetMapping("/forward")
    public void forward(HttpServletRequest request , HttpServletResponse response , String url) throws Exception {
        RequestDispatcher dispatcher = request.getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    @RequestMapping("/index")
    // 加上这个注解，会直接把string返回到前端
    @ResponseBody
    public String index(){
        return "index";
    }

    // safeRedirect
    @RequestMapping("/safeRedirect")
    @ResponseBody
    public String safeRedirect(HttpServletRequest request ) {
        String url = request.getParameter("url");
        if (SecurityCheck.checkUrl(url)) {
            return "redirect:" + url;
        }
        // 无效的url
        return "invalid url! ";
    }
}
